<template>
  <div class="articles-reply-container">
    <!-- 搜索栏 -->
    <el-row class="search-row">
      <el-col :span="8">
        <el-input
          v-model.number="searchParams.articleId" 
          placeholder="请输入文章ID" 
          style="width: 100%;"
        ></el-input>
      </el-col>
      <el-col :span="8">
        <el-button
          type="danger"
          size="large"
          @click="loadReplyList"
          style="margin-right: 10px;"
        >
          <i class="el-icon-search"></i> 搜索
        </el-button>
        <el-button
          type="primary"
          size="large"
          @click="showAddDialog"
        >
          <i class="el-icon-circle-plus"></i> 添加回复
        </el-button>
      </el-col>
    </el-row>

    <!-- 添加回复对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加文章回复"
      width="500px"
    >
      <el-form :model="addForm" label-width="120px">
        <el-form-item label="文章ID" :rules="{ required: true, message: '请输入文章ID', trigger: 'blur' }">
          <el-input 
            v-model.number="addForm.articleId" 
            autocomplete="off"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户ID" :rules="{ required: true, message: '请输入用户ID', trigger: 'blur' }">
          <el-input 
            v-model.number="addForm.userId" 
            autocomplete="off"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item label="回复内容" :rules="{ required: true, message: '请输入回复内容', trigger: 'blur' }">
          <el-input 
            type="textarea" 
            v-model="addForm.content" 
            autocomplete="off"
            :rows="4"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addReply">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑回复对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑文章回复"
      width="500px"
    >
      <el-form :model="editForm" label-width="120px">
        <el-form-item label="回复ID">
          <el-input v-model="editForm.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="文章ID" :rules="{ required: true, message: '请输入文章ID', trigger: 'blur' }">
          <el-input 
            v-model.number="editForm.articleId" 
            autocomplete="off"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户ID" :rules="{ required: true, message: '请输入用户ID', trigger: 'blur' }">
          <el-input 
            v-model.number="editForm.userId" 
            autocomplete="off"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item label="回复内容" :rules="{ required: true, message: '请输入回复内容', trigger: 'blur' }">
          <el-input 
            type="textarea" 
            v-model="editForm.content" 
            autocomplete="off"
            :rows="4"
          ></el-input>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input 
            v-model="editForm.createTime" 
            disabled 
            :value="formatTime(editForm.createTime)" 
          ></el-input>
        </el-form-item>
        <el-form-item label="更新时间">
          <el-date-picker
            v-model="editForm.updateTime"
            type="datetime"
            placeholder="选择更新时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateReply">确定</el-button>
      </template>
    </el-dialog>

    <!-- 状态容器 -->
    <div class="state-container">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-mask">
        <el-loading-spinner size="large"></el-loading-spinner>
        <p>正在加载数据，请稍候...</p>
      </div>

      <!-- 空数据提示 -->
      <div v-else-if="replyList.length === 0" class="empty-data">
        <i class="el-icon-data-empty"></i>
        <p>暂无回复数据</p>
        <el-button type="primary" @click="loadReplyList">刷新</el-button>
      </div>

      <!-- 错误提示 -->
      <div v-else-if="errorMessage" class="error-message">
        <i class="el-icon-error"></i>
        <p>{{ errorMessage }}</p>
        <el-button type="primary" @click="loadReplyList">重试</el-button>
      </div>

      <!-- 文章回复列表 -->
      <el-table
        v-else
        :data="replyList"
        stripe
        highlight-current-row
        border
        style="width: 100%; margin-top: 20px;"
      >
        <el-table-column
          prop="id"
          label="回复ID"
          min-width="100px"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="articleId"
          label="文章ID"
          min-width="100px"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="userId"
          label="用户ID"
          min-width="100px"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="content"
          label="回复内容"
          min-width="250px"
          align="left"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          min-width="180px"
          align="center"
        >
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="updateTime"
          label="更新时间"
          min-width="180px"
          align="center"
        >
          <template #default="scope">
            {{ formatTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          min-width="150px"
          align="center"
        >
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="showEditDialog(scope.row)"
              style="margin-right: 5px;"
            >
              <i class="el-icon-edit"></i> 编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteRow(scope.row)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
        v-else
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.page"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="pagination.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        style="margin-top: 20px;"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { useUserInfoStore } from "../pinia/userinfo"

export default {
  data() {
    return {
      replyList: [], 
      searchParams: {
        articleId: null,
        page: 1,
        limit: 10
      },
      sprheaders: {
        uname: "",
        token: ""
      },
      addDialogVisible: false, 
      editDialogVisible: false, 
      addForm: {
        articleId: null,
        userId: null,
        content: ''
      }, 
      editForm: {
        id: '',
        articleId: null,
        userId: null,
        content: '',
        createTime: '',
        updateTime: ''
      }, 
      pagination: {
        page: 1,
        limit: 10,
        total: 0
      },
      loading: false,
      errorMessage: ''
    }
  },
  created() {
    const userStore = useUserInfoStore();
    this.sprheaders.uname = userStore.getUsername
    this.sprheaders.token = userStore.getToken
  },
  methods: {
    // 加载文章回复列表
    loadReplyList() {
      if (this.searchParams.articleId === null) {
        this.$message.warning('请先选择文章ID');
        return;
      }
      
      this.loading = true;
      this.errorMessage = '';
      
      const params = {
        articleId: this.searchParams.articleId,
      };

      console.log('请求参数:', params);
      console.log('请求URL:', this.$baseUrl.SPRURL + "v2/articles/getReplyList");
      console.log('请求头:', this.sprheaders);
      
      axios.get(this.$baseUrl.SPRURL + "v2/articles/getReplyList", {
        headers: this.sprheaders,
        params: params
      })
      .then(res => {
        console.log('API响应:', res);
        
        if (res.data.code === 0) {
          this.replyList = res.data.data || [];
          this.replyList.forEach(item => {
            // 确保数值类型正确
            item.id = Number(item.id);
            item.articleId = Number(item.articleId);
            item.userId = Number(item.userId);
            
            // 处理时间格式（如果后端只返回时分秒，补全日期）
            if (item.createTime && item.createTime.length === 8) { // 检查是否只有"HH:mm:ss"
              const today = new Date().toISOString().split('T')[0];
              item.createTime = `${today} ${item.createTime}`;
            }
            
            if (item.updateTime && item.updateTime.length === 8) { // 检查是否只有"HH:mm:ss"
              const today = new Date().toISOString().split('T')[0];
              item.updateTime = `${today} ${item.updateTime}`;
            }
          });
          
          this.pagination.total = res.data.count || 0; 
        } else {
          this.errorMessage = res.data.msg || '数据加载失败';
        }
      })
      .catch(error => {
        console.error('API请求错误:', error);
        
        if (error.response) {
          this.errorMessage = `请求错误 ${error.response.status}: ${error.response.data.message || error.response.statusText}`;
          console.error('响应数据:', error.response.data);
        } else if (error.request) {
          this.errorMessage = '没有收到服务器响应';
        } else {
          this.errorMessage = '请求发生错误: ' + error.message;
        }
      })
      .finally(() => {
        this.loading = false;
      });
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.pagination.limit = val;
      this.pagination.page = 1;
      this.loadReplyList();
    },

    // 分页页码变化
    handleCurrentChange(val) {
      this.pagination.page = val;
      this.loadReplyList();
    },

    // 显示添加对话框
    showAddDialog() {
      this.addForm = { 
        articleId: this.searchParams.articleId,
        userId: null,
        content: ''
      };
      this.addDialogVisible = true;
    },

    // 显示编辑对话框
    showEditDialog(row) {
      this.editDialogVisible = true;
      this.editForm = { 
        id: row.id,
        articleId: row.articleId,
        userId: row.userId,
        content: row.content,
        createTime: row.createTime,
        updateTime: row.updateTime
      };
    },

    // 添加文章回复
    addReply() {
      this.$refs.addForm.validate((valid) => {
        if (!valid) {
          this.$message.warning('请填写所有必填字段');
          return;
        }

        const payload = {
          ...this.addForm,
          articleId: Number(this.addForm.articleId),
          userId: Number(this.addForm.userId)
        };

        console.log('添加回复请求数据:', payload);
        
        axios.post(this.$baseUrl.SPRURL + "v2/articles/articlesreply", payload, {
          headers: this.sprheaders
        })
        .then(res => {
          console.log('添加回复响应:', res);
          
          if (res.data.code === 0) {
            this.$message.success('回复添加成功');
            this.addDialogVisible = false;
            this.loadReplyList();
          } else {
            this.$message.error(res.data.msg || '回复添加失败');
          }
        })
        .catch(error => {
          console.error('添加回复错误:', error);
          this.$message.error('网络请求失败，请重试');
        });
      });
    },

    // 更新文章回复
    updateReply() {
      this.$refs.editForm.validate((valid) => {
        if (!valid) {
          this.$message.warning('请填写所有必填字段');
          return;
        }

        const payload = {
          ...this.editForm,
          articleId: Number(this.editForm.articleId),
          userId: Number(this.editForm.userId),
          // 确保时间格式正确
          updateTime: this.formatTimeForApi(this.editForm.updateTime)
        };

        console.log('更新回复请求数据:', payload);
        
        axios.put(this.$baseUrl.SPRURL + "v2/articles/articlesreply", payload, {
          headers: this.sprheaders
        })
        .then(res => {
          console.log('更新回复响应:', res);
          
          if (res.data.code === 0) {
            this.$message.success('回复更新成功');
            this.editDialogVisible = false;
            this.loadReplyList();
          } else {
            this.$message.error(res.data.msg || '回复更新失败');
          }
        })
        .catch(error => {
          console.error('更新回复错误:', error);
          this.$message.error('网络请求失败，请重试');
        });
      });
    },

    // 删除文章回复
    deleteRow(row) {
      this.$confirm('确认删除该回复吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        console.log('删除回复ID:', row.id);
        
        axios.delete(this.$baseUrl.SPRURL + `v2/articles/articlesreply/${row.id}`, {
          headers: this.sprheaders
        })
        .then(res => {
          console.log('删除回复响应:', res);
          
          if (res.data.code === 0) {
            this.$message.success('回复删除成功');
            this.loadReplyList();
          } else {
            this.$message.error(res.data.msg || '回复删除失败');
          }
        })
        .catch(error => {
          console.error('删除回复错误:', error);
          this.$message.error('网络请求失败，请重试');
        });
      })
      .catch(() => {
        this.$message.info('已取消删除');
      });
    },

    // 格式化时间显示（用于表格和输入框）
    formatTime(timeStr) {
      if (!timeStr) return '';
      
      // 处理Date对象或字符串
      const date = typeof timeStr === 'string' ? new Date(timeStr) : timeStr;
      
      // 确保日期有效
      if (isNaN(date.getTime())) return timeStr;
      
      // 格式化为 YYYY-MM-DD HH:mm:ss
      return date.toISOString()
        .replace('T', ' ')
        .replace(/\.\d{3}/, '');
    },

    // 格式化时间用于API请求
    formatTimeForApi(time) {
      if (!time) return null;
      
      // 如果是Date对象，转换为字符串
      if (time instanceof Date) {
        return time.toISOString()
          .replace('T', ' ')
          .replace(/\.\d{3}/, '');
      }
      
      // 如果已经是字符串，直接返回
      return time;
    }
  }
}
</script>

<style scoped>
.articles-reply-container {
  padding: 20px;
  background-color: #f8f9fa;
  min-height: 400px;
  position: relative;
}

.search-row {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
}

.el-table {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.el-pagination {
  margin-top: 30px;
  text-align: right;
}

/* 状态容器样式 */
.state-container {
  min-height: 300px;
  position: relative;
}

/* 加载状态样式 */
.loading-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 10;
}

/* 空数据提示样式 */
.empty-data {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 10;
  color: #909399;
}

.empty-data i {
  font-size: 40px;
  margin-bottom: 10px;
}

.empty-data p {
  margin-bottom: 20px;
  font-size: 16px;
}

/* 错误提示样式 */
.error-message {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 10;
  color: #f56c6c;
}

.error-message i {
  font-size: 40px;
  margin-bottom: 10px;
}

.error-message p {
  margin-bottom: 20px;
  font-size: 16px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-row el-col {
    span: 24;
  }
  .el-table el-table-column {
    min-width: auto;
  }
}
</style>  